from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

"""
横坐标数据
纵坐标数据
图例
标题
是否显示数值
数值位置
# 设置字体为支持中文的字体，例如：'SimHei'（黑体）、'Microsoft YaHei'（微软雅黑）等  
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签  
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号 
"""


class BarChartTools:

    def __init__(self):
        # 创建 matplotlib 图形
        self.categories = None
        self.values = None
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
        # 添加子图和绘制数据
        self.ax = self.fig.add_subplot(111)
        plt.xticks(fontsize=4)
        # self.values = values
        # self.categories = categories
        # self.bars = self.ax.bar([], [])  # 保存柱子引用以便后续更新
        #
        # # 显示对应的值
        # for c,v in zip(categories,values):
        #     self.ax.text(c,v,str(v),ha='center',va='bottom')

        # # 连接点击事件
        # if clicked_handle is not None:
        #     self.canvas.mpl_connect('button_press_event', clicked_handle)

    def update_data(self, categories, values, xticks=[], clicked_handle=None):
        self.ax.clear()
        self.values = values
        self.categories = categories
        self.bars = self.ax.bar(categories, values)  # 保存柱子引用以便后续更新
        if len(xticks) > 0:
            self.ax.set_xticks(categories)
        # 显示对应的值
        for c, v in zip(categories, values):
            self.ax.text(c, v, str(v), ha='center', va='bottom')

        # 连接点击事件
        if clicked_handle is not None:
            self.canvas.mpl_connect('button_press_event', clicked_handle)
        # 绘制
        # self.fig.draw()

        # self.canvas.draw()
        self.canvas.draw_idle()
        # 连接点击事件
        if clicked_handle is not None:
            self.canvas.mpl_connect('button_press_event', clicked_handle)

    def clicked_item_value(self, event):
        """
        获取点的柱状图的值
        :param event:
        :return:
        """

        if event.inaxes is None:
            return
        # 获取点击位置的 x 坐标
        x_click = event.xdata
        # 获取点击位置的 y 坐标
        y_click = event.ydata
        # bar_x <= x_click <= bar_x + bar_width
        # bar_y <= y_click <= bar_y + bar_height
        for bar in self.bars:
            if (x_click >= bar.get_x() and x_click <= bar.get_x() + bar.get_width()) and (
                    y_click >= bar.get_y() and y_click <= bar.get_y() + bar.get_height()):
                return self.values[self.bars.index(bar)]

    def clicked_item_category(self, event):
        if event.inaxes is None:
            return
        # 获取点击位置的 x 坐标
        x_click = event.xdata
        # 获取点击位置的 y 坐标
        y_click = event.ydata
        # bar_x <= x_click <= bar_x + bar_width
        # bar_y <= y_click <= bar_y + bar_height
        for bar in self.bars:
            if (x_click >= bar.get_x() and x_click <= bar.get_x() + bar.get_width()) and (
                    y_click >= bar.get_y() and y_click <= bar.get_y() + bar.get_height()):
                return self.categories[self.bars.index(bar)]

    # def show_value(self,align="top"):
    #     if align == "top":

    def default_item(self, defaults_index=[], color='red') -> None:
        """
        设置柱状图默认选择颜色
        :param defaults_index: 默认柱状图 索引
        :param color: 默认红色
        :return: None
        """
        if len(defaults_index) != 0:
            for index in defaults_index:
                self.bars[index].set_color(color)

    def set_title(self, title):
        """
        设置标题
        :param title: 标题
        :return:
        """
        self.ax.set_title(title)

    def clear_axes(self):
        self.ax.clear()
        self.canvas.draw_idle()
